#include <Arduino.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
// 2022.6.14——ESP01S  知心天气 调试完成
/* ////////////////////////////////////////////////
    实验板：ESP01S
    版本：V0.1
    更改内容:
        V0.1：知心天气 调试完成
            1.修复了json解析有一部分不能使用的问题
            2.问题：应该是定义类的问题，导致外部不能调用
            3.可以把daily下的每一个{}当成一个数组来处理[0][1][2]即可
            4.去掉循环，直接每个数组都调用一边，注意变量名的变化
            私钥：SeiP2ViJVtkngR1s5
            接口地址//https://api.seniverse.com/
                              v3/weather/now.json?
                              key=your_api_key
                              &location=beijing
                              &language=zh-Hans
                              &unit=c
                              &start=0
                              &days=3
*/
////////////////////////////////////////////////

// WiFi settings
const char *ssid = "123456";
const char *password = "776654321";
const char *host = "api.seniverse.com"; // API server

WiFiClient client;
int httpPort = 80;

String key = "SeiP2ViJVtkngR1s5";
String location = "luoyang";
String language = "zh-Hans";
String jsonAnswer;

void client_respon()
{
  String answer;
  int jsonIndex;
  if (!client.connect(host, httpPort)) // TCP连接是否成功，不成功再重试
  {
    Serial.println("connection failed");
    return;
  }

  //!请求网址
  String url = "/v3/weather/daily.json?key=" + key + "&location=" + location + "&language=" + language + "&unit=c&start=0&days=3";
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(100);
  //将每行的返回值加入到answer
  while (client.available())
  {
    String line = client.readStringUntil('\r'); // terminator: 终止字符。用于设置终止函数执行的字符信息。设备在读取数据时一旦读取到此终止字符，将会结束函数执行。允许使用char类型。
    answer += line;
  }
  client.stop(); //关闭连接
  //!以下为将string数据answer处理为json
  for (int i = 0; i < answer.length(); i++) //如果开头为{目录就为i
  {
    if (answer[i] == '{')
    {
      jsonIndex = i;
      break;
    }
  }
  jsonAnswer = answer.substring(jsonIndex);
}

void setup()
{
  Serial.begin(115200);
  delay(10);
  // WIFI开始连接
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) //等待wifi连接成功
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop()
{
  client_respon();

  // String input;
  DynamicJsonDocument doc(1536);
  DeserializationError error = deserializeJson(doc, jsonAnswer);
  JsonObject results_0 = doc["results"][0];

  JsonObject results_0_location = results_0["location"];
  const char *results_0_location_path = results_0_location["path"];         // "洛阳,洛阳,河南,中国"
  const char *results_0_location_timezone = results_0_location["timezone"]; // "Asia/Shanghai"

  //!关键点，把daily下的每一个{}视为数组调用，现在调用的是今天的数据
  JsonObject results_0_daily_item0 = results_0["daily"][0];
  const char *results_0_daily_item0_date = results_0_daily_item0["date"];                                   //日期
  const char *results_0_daily_item0_text_day = results_0_daily_item0["text_day"];                           //白天天气现象文字
  const char *results_0_daily_item0_text_night = results_0_daily_item0["text_night"];                       //晚间天气现象文字
  const char *results_0_daily_item0_high = results_0_daily_item0["high"];                                   //当天最高温度
  const char *results_0_daily_item0_low = results_0_daily_item0["low"];                                     //当天最低温度
  const char *results_0_daily_item0_rainfall = results_0_daily_item0["rainfall"];                           //降水量，单位mm
  const char *results_0_daily_item0_precip = results_0_daily_item0["precip"];                               //降水概率，范围0~100，单位百分比
  const char *results_0_daily_item0_wind_direction = results_0_daily_item0["wind_direction"];               //风向文字
  const char *results_0_daily_item0_wind_direction_degree = results_0_daily_item0["wind_direction_degree"]; //风向角度，范围0~360
  const char *results_0_daily_item0_wind_speed = results_0_daily_item0["wind_speed"];                       //风速，单位km/h
  const char *results_0_daily_item0_wind_scale = results_0_daily_item0["wind_scale"];                       //风力等级
  const char *results_0_daily_item0_humidity = results_0_daily_item0["humidity"];                           //相对湿度，0~100，单位为百分比

  JsonObject results_0_daily_item1 = results_0["daily"][1];
  const char *results_0_daily_item1_date = results_0_daily_item1["date"];                                   //日期
  const char *results_0_daily_item1_text_day = results_0_daily_item1["text_day"];                           //白天天气现象文字
  const char *results_0_daily_item1_text_night = results_0_daily_item1["text_night"];                       //晚间天气现象文字
  const char *results_0_daily_item1_high = results_0_daily_item1["high"];                                   //当天最高温度
  const char *results_0_daily_item1_low = results_0_daily_item1["low"];                                     //当天最低温度
  const char *results_0_daily_item1_rainfall = results_0_daily_item1["rainfall"];                           //降水量，单位mm
  const char *results_0_daily_item1_precip = results_0_daily_item1["precip"];                               //降水概率，范围0~100，单位百分比
  const char *results_0_daily_item1_wind_direction = results_0_daily_item1["wind_direction"];               //风向文字
  const char *results_0_daily_item1_wind_direction_degree = results_0_daily_item1["wind_direction_degree"]; //风向角度，范围0~360
  const char *results_0_daily_item1_wind_speed = results_0_daily_item1["wind_speed"];                       //风速，单位km/h
  const char *results_0_daily_item1_wind_scale = results_0_daily_item1["wind_scale"];                       //风力等级
  const char *results_0_daily_item1_humidity = results_0_daily_item1["humidity"];                           //相对湿度，0~100，单位为百分比

  JsonObject results_0_daily_item2 = results_0["daily"][2];
  const char *results_0_daily_item2_date = results_0_daily_item2["date"];                                   //日期
  const char *results_0_daily_item2_text_day = results_0_daily_item2["text_day"];                           //白天天气现象文字
  const char *results_0_daily_item2_text_night = results_0_daily_item2["text_night"];                       //晚间天气现象文字
  const char *results_0_daily_item2_high = results_0_daily_item2["high"];                                   //当天最高温度
  const char *results_0_daily_item2_low = results_0_daily_item2["low"];                                     //当天最低温度
  const char *results_0_daily_item2_rainfall = results_0_daily_item2["rainfall"];                           //降水量，单位mm
  const char *results_0_daily_item2_precip = results_0_daily_item2["precip"];                               //降水概率，范围0~100，单位百分比
  const char *results_0_daily_item2_wind_direction = results_0_daily_item2["wind_direction"];               //风向文字
  const char *results_0_daily_item2_wind_direction_degree = results_0_daily_item2["wind_direction_degree"]; //风向角度，范围0~360
  const char *results_0_daily_item2_wind_speed = results_0_daily_item2["wind_speed"];                       //风速，单位km/h
  const char *results_0_daily_item2_wind_scale = results_0_daily_item2["wind_scale"];                       //风力等级
  const char *results_0_daily_item2_humidity = results_0_daily_item2["humidity"];                           //相对湿度，0~100，单位为百分比

  const char *results_0_last_update = results_0["last_update"]; // "2022-06-14T08:00:00+08:00"
  Serial.print(results_0_daily_item0_date);
  Serial.print(results_0_daily_item1_date);
  Serial.println(results_0_daily_item2_date);

  Serial.print(results_0_daily_item0_text_day);
  Serial.print(results_0_daily_item1_text_day);
  Serial.println(results_0_daily_item2_text_day);

  delay(2000);
}
